//
//  HTTPClient.m
//  storeapp
//
//  Created by huangyi on 13-12-27.
//  Copyright (c) 2013年 ios. All rights reserved.
//

#import "HTTPClient.h"
#import "Fmwk.h"

@implementation HTTPClient

-(void)parse:(NSHTTPURLResponse*)response{/*override*/}

-(NSString*)description{
    NSMutableString *string=[NSMutableString string];
    [string appendFormat:@"%@: %@\n",self.requestObject.HTTPMethod,self.fullURLString];
    if (self.requestObject.HTTPBody) {
        NSString *requestText=[[NSString alloc] initWithData:self.requestObject.HTTPBody encoding:NSUTF8StringEncoding];
        if (requestText) {
            [string appendFormat:@"%@ \n",requestText];
        }
    }
    [string appendFormat:@"Code: %@\n",@(self.statusCode)];
    [string appendFormat:@"Message: %@\n",self.message];
    NSRange r=[self.responseContentType rangeOfString:@"text"];
    if (r.length!=0) {
        NSString *responseText=[[NSString alloc] initWithData:self.responseData encoding:NSUTF8StringEncoding];
        [string appendFormat:@"%@: \n%@",self.responseContentType,responseText];
    }else{
        [string appendFormat:@"%@: \n%@",self.responseContentType,self.responseData];
    }
    return string;
}

-(instancetype)initWithURLString:(NSString *)fullstring{
    self=[super init];
    if (self) {
        if ([fullstring rangeOfString:@"http://"].location==NSNotFound) {
            fullstring=[NSString stringWithFormat:@"http://%@",fullstring];
        }
        _fullURLString=fullstring;
        NSURL *url=[NSURL URLWithString:fullstring];
        if (!url) {
            return nil;
        }

        _requestObject=[[NSMutableURLRequest alloc] initWithURL:url];
        _responseHeaderFields=nil;
        _responseData=nil;
        _error=nil;

        [self setHTTPMethod:@"GET"];
        [self setContentType:@"application/octet-stream; charset=utf-8"];
        [self setHeaderField:@"Connection" withValue:@"Keep-Alive"];
        [self setGZipData:NO];
    }
    return self;
}
-(void)execute{
    [self executeNoOutput];
}
-(void)executeNoOutput{
    NSHTTPURLResponse *response=nil;
    NSError *error=nil;
    NSData *result=[NSURLConnection sendSynchronousRequest:self.requestObject returningResponse:&response error:&error];
    if (error) {
        _statusCode=-1;
        self.message=error.localizedDescription;
        self.error=error;
    }else{
        _statusCode=response.statusCode;
        self.message=[NSHTTPURLResponse localizedStringForStatusCode:response.statusCode];
        if (self.statusCode!=200) {
            self.error=[NSError errorWithDomain:NSGenericException code:-1 userInfo:@{NSLocalizedDescriptionKey:self.message}];
        }
        NSDictionary *headerFields=[response allHeaderFields];
        _responseHeaderFields=headerFields;
        _responseContentType=headerFields[@"Content-Type"];
        _responseData=result;
        [self parse:response];
    }
}

-(void)setHTTPMethod:(NSString*)method{
    [self.requestObject setHTTPMethod:method];
}
-(void)setContentType:(NSString*)type{
    [self setHeaderField:@"Content-Type" withValue:type];
}
-(void)setHeaderField:(NSString*)header withValue:(id)object{
    NSString *value=[NSString stringWithFormat:@"%@",object];
    [self.requestObject setValue:value forHTTPHeaderField:header];
}
-(void)setTimeoutInterval:(NSTimeInterval)seconds{
    [self.requestObject setTimeoutInterval:seconds];
}
-(void)setPostData:(NSData*)data{
    [self setHTTPMethod:@"POST"];
    if (self.gzip) {
        [NSException raise:@"TODO" format:@"gzip"];
    }
    [self setHeaderField:@"Content-Length" withValue:@(data.length)];
    [self.requestObject setHTTPBody:data];
}

-(void)setGZipData:(BOOL)gz{
    _gzip=gz;
}

-(void)setMultipartForm:(BOOL)mp{
    _multipart=mp;
}

-(BOOL)detectFormType:(NSDictionary*)form{
    BOOL multipart=self.multipart;
    if (!multipart) {
        NSArray *vals=[form allValues];
        for (id obj in vals) {
            if ([obj isKindOfClass:[NSData class]]) {
                multipart=YES;
            }
            if ([obj isKindOfClass:[UIImage class]]) {
                multipart=YES;
            }
        }
    }
    return multipart;
}
-(void)setPostObject:(NSDictionary*)form{
    [self setHTTPMethod:@"POST"];
    BOOL multipart=[self detectFormType:form];
    if (multipart) {
        NSData *data=[self buildMultipartDictionary:form];
        [self setPostData:data];
    }else{
        NSData *data=[self buildFormDictionary:form];
        [self setPostData:data];
    }
}

-(NSData*)buildFormDictionary:(NSDictionary*)form{
    [self setContentType:@"application/x-www-form-urlencoded; charset=utf-8"];
    NSMutableString *string=[NSMutableString string];
    NSArray *keys=[form allKeys];
    for (int i=0; i<keys.count;i++) {
        @autoreleasepool {
            if (i>0) {
                [string appendString:@"&"];
            }
            NSString *k=[keys objectAtIndex:i];
            NSString *v=nil;
            id obj=[form valueForKey:k];
            if ([obj isKindOfClass:[NSString class]]) {
                v=obj;
            }
            if ([obj isKindOfClass:[NSNumber class]]) {
                v=[obj stringValue];
            }
            if ([obj isKindOfClass:[NSDictionary class]]) {
                NSDictionary *json=obj;
                v=[json JSONString];
            }
            if ([obj isKindOfClass:[NSArray class]]) {
                NSArray *json=obj;
                v=[json JSONString];
            }
            [string appendString:k];
            [string appendString:@"="];
            NSString *enc=v.urlencode;
            if (enc) {
                [string appendString:v.urlencode];
            }
        }
    }
    return [string dataUsingEncoding:NSUTF8StringEncoding];
}

NSString *const multipartFormEOL=@"--";
NSString *const multipartFormNewLine=@"\r\n";
NSString *const multipartFormBoundary=@"---------------------------0xKmUlTiPaRtFoRmBoUnDaRy";
-(NSData*)buildMultipartDictionary:(NSDictionary*)form{
    [NSException raise:@"TODO" format:@"buildMultipartDictionary"];
    return nil;
}

@end
